package com.sgb.kjwl.view.ui.activity.self.carMaster;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityEditSubPathBinding;
import com.sgb.kjwl.model.entity.self.CarriageSelectEntity;
import com.sgb.kjwl.model.entity.self.GoodsSelectEntity;
import com.sgb.kjwl.model.entity.self.OwnPathEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.self.SubSetListEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.view.ui.adapter.self.carMasters.SubscriptionSetAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.view.widget.transport.ChooseTypePopWindow;
import com.sgb.kjwl.viewmodel.self.carMakers.EditSubPathModel;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/6/18
 */
public class EditSubscribePathActivity extends AppActivity {

    private EditSubPathModel viewModel;
    private boolean isEdit;
    private ActivityEditSubPathBinding mBinding;
    private OwnPathEntity pathEntity;
    private SubscriptionSetAdapter mAdapter;

    //地址选择器
    private OptionsPickerView mAddressPicker;
    private ChooseTypePopWindow goodsTypePop;
    private ChooseTypePopWindow carsTypePop;
    //选择的位置：0-装货地,1-卸货地，2—货物类型，3—车型
    private int mSelectIndex = -1;
    //标签列表
    private List<SubSetListEntity> mList = new ArrayList<>();
    private List<TypeChooseEntity> goodsTypeEntities = new ArrayList<>();
    private List<TypeChooseEntity> carTypeEntities = new ArrayList<>();
    private List<TypeChooseEntity> goodsTypeEditeList = new ArrayList<>();

    public static void start(Context context, boolean isEdit, OwnPathEntity entity) {
        Intent intent = new Intent(context, EditSubscribePathActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("isEdit", isEdit);
        intent.putExtra("entity", entity);
        context.startActivity(intent);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, EditSubscribePathActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        isEdit = getIntent().getBooleanExtra("isEdit", false);
        pathEntity = (OwnPathEntity) getIntent().getSerializableExtra("entity");

        viewModel = new ViewModelProvider(this).get(EditSubPathModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_sub_path);
        mBinding.include.titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
        mBinding.include.ivBack.setOnClickListener(v -> finish());

        mBinding.chooseCarType.setOnClickListener(this::onMultiClick);
        mBinding.chooseGoodsType.setOnClickListener(this::onMultiClick);
        mBinding.submitBtn.setOnClickListener(this::onMultiClick);

        if (isEdit && pathEntity != null) {
            mBinding.include.titleView.setText("编辑路线");
            mBinding.include.rightView.setText("删除路线");
            mBinding.include.rightView.setVisibility(View.VISIBLE);
            mBinding.include.rightView.setOnClickListener(this);
            mBinding.editUsedLayout.setVisibility(View.VISIBLE);
            mBinding.newPathAlter.setVisibility(View.GONE);
        } else {
            mBinding.include.titleView.setText("新增线路");
            mBinding.include.rightView.setVisibility(View.GONE);
            mBinding.editUsedLayout.setVisibility(View.GONE);
            mBinding.newPathAlter.setVisibility(View.VISIBLE);
        }
        initPicker();
        initRecycler();
        initEvent();
        if (pathEntity != null) {
            loadingData(pathEntity);
            if (pathEntity.getGoodsType()!=null&&pathEntity.getGoodsType().size()>0) {
                viewModel.checkGoodsType(pathEntity.getGoodsType());
            }
        } else {
            viewModel.getGoodsTypeList();
            initTags();
        }
        iniData();
    }

    private void iniData() {
        viewModel.getCarTypeList(null);
    }

    private void initEvent() {
        mAdapter.addCallBack(parentIndex -> {
            mSelectIndex = parentIndex;
            String titleName = "";
            if (mAddressPicker != null)

            if (mSelectIndex==0){
                titleName="选择装货地";
            }else if (mSelectIndex==1){
                titleName="选择目的地";
            }
                mAddressPicker.setTitleText(titleName);
                mAddressPicker.show();
        });

        viewModel.deleteLD.observe(this, aBoolean -> {
            MToast.showToast(EditSubscribePathActivity.this, "删除成功");
            finish();
        });
        viewModel.saveLD.observe(this, aBoolean -> {
            MToast.showToast(EditSubscribePathActivity.this, "操作成功");
            finish();
        });
        viewModel.selectData.observe(this, select->{
            viewModel.getGoodsTypeList();
            if (select!=null){
                setGoodsTypeData(select);
            }
        });
        viewModel.packagingLD.observe(this, entity -> submitData(entity));
        viewModel.goodsTypeLD.observe(this, goodsSelectEntities -> loadingGoodsType(goodsSelectEntities));
        viewModel.carTypeLD.observe(this, goodsInfoTypeEntity3s -> loadingCarsType(goodsInfoTypeEntity3s));
        goodsTypePop = new ChooseTypePopWindow(this, "货物类型");
        goodsTypePop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
                inputGoodsType(entity);
            }
        });
        carsTypePop = new ChooseTypePopWindow(this, "车型");
        carsTypePop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
                inputCarType(entity);
            }
        });
    }

    /**
     * 输入车型
     *
     * @param entity
     */
    private void inputCarType(List<TypeChooseEntity> entity) {
        if (entity == null)
            return;
        carTypeEntities.clear();
        carTypeEntities.addAll(entity);
        String carTypeStr = "";

        if (entity.size() > 0) {
            for (TypeChooseEntity typeEntity : carTypeEntities) {
                if (!TextUtils.isEmpty(typeEntity.getName())) {
                    carTypeStr = carTypeStr + typeEntity.getName() + "/";
                }
            }
        }
        if (!TextUtils.isEmpty(carTypeStr)) {
            carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
        }

        if (TextUtils.isEmpty(carTypeStr)) {
            mBinding.chooseCarType.setText("请选择车型");
            mBinding.chooseCarType.setTextColor(this.getResources().getColor(R.color.color_C0C4CC));
        } else {
            mBinding.chooseCarType.setText(carTypeStr);
            mBinding.chooseCarType.setTextColor(this.getResources().getColor(R.color.color_ff666666));
        }
    }

    /**
     * 输入货物类型
     *
     * @param entity
     */
    private void inputGoodsType(List<TypeChooseEntity> entity) {
        if (entity == null)
            return;
        goodsTypeEntities.clear();
        goodsTypeEntities.addAll(entity);
        if (carsTypePop.getmAdapter() != null) {
            carsTypePop.getmAdapter().clearSelects();
        }
        inputCarType(new ArrayList<>());
        String carTypeStr = "";

        for (TypeChooseEntity typeEntity : goodsTypeEntities) {
            if (!TextUtils.isEmpty(typeEntity.getName())) {
                carTypeStr = carTypeStr + typeEntity.getName() + "/";
            }
        }
        if (carTypeStr.length() > 0) {
            carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
        }

        if (TextUtils.isEmpty(carTypeStr)) {
            mBinding.chooseGoodsType.setText("请选择货物类型");
            mBinding.chooseGoodsType.setTextColor(this.getResources().getColor(R.color.color_C0C4CC));
        } else {
            mBinding.chooseGoodsType.setText(carTypeStr);
            mBinding.chooseGoodsType.setTextColor(this.getResources().getColor(R.color.color_ff666666));
        }
        if (goodsTypeEntities.size() > 0) {
            viewModel.getCarTypeList(goodsTypeEntities);
        } else {
            viewModel.getCarTypeList(null);
        }


    }

    /**
     * 填充车型window
     *
     * @param goodsTypeEntity3s
     */
    private void loadingCarsType(List<GoodsInfoTypeEntity3> goodsTypeEntity3s) {
        if (goodsTypeEntity3s == null) {
            return;
        }
        List<TypeChooseEntity> typeEntities = new ArrayList<>();
        for (int i = 0; i < goodsTypeEntity3s.size(); i++) {
            TypeChooseEntity typeEntity = new TypeChooseEntity();
            typeEntity.setSelect(false);
            typeEntity.setName(goodsTypeEntity3s.get(i).getName());
            typeEntity.setNo(goodsTypeEntity3s.get(i).getNo());
            if (isEdit && carTypeEntities.size() > 0) {
                for (TypeChooseEntity entity : carTypeEntities) {
                    if (entity.getNo().equals(typeEntity.getNo())) {
                        typeEntity.setSelect(true);
                    }
                }
            }
            typeEntities.add(typeEntity);
        }
        carsTypePop.setData(typeEntities);
    }

    /**
     * 填充货物类型window
     *
     * @param goodsSelectEntities
     */
    private void loadingGoodsType(List<GoodsSelectEntity> goodsSelectEntities) {
        if (goodsSelectEntities == null) {
            return;
        }
        List<TypeChooseEntity> typeEntities = new ArrayList<>();
        for (int i = 0; i < goodsSelectEntities.size(); i++) {
            TypeChooseEntity typeEntity = new TypeChooseEntity();
            typeEntity.setSelect(false);
            typeEntity.setName(goodsSelectEntities.get(i).getName());
            typeEntity.setNo(goodsSelectEntities.get(i).getNo());
            if (isEdit &&goodsTypeEntities.size()>0?goodsTypeEntities.size() > 0:goodsTypeEditeList.size()>0) {
                for (TypeChooseEntity entity :goodsTypeEntities.size()>0? goodsTypeEntities:goodsTypeEditeList) {
                    if (entity.getNo().equals(typeEntity.getNo())) {
                        typeEntity.setSelect(true);
                    }
                }
            }
            typeEntities.add(typeEntity);
        }
        goodsTypePop.setData(typeEntities);
    }

    /**
     * 提交数据
     *
     * @param entity
     */
    private void submitData(OwnPathEntity entity) {
        //判断是否需要改变启用状态
        if (isEdit) {
            if (mBinding.switchBtn.isChecked()) {
                entity.setStatus("1");
            } else
                entity.setStatus("0");
        }
        viewModel.addOrEditPath(this, entity);
    }


    private void initPicker() {
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {
                mAddressPicker = PickerHelper.with(EditSubscribePathActivity.this)
                        .getCommonPicker(provinceList, cityList, (options1, options2, options3, v) -> {
                            AddressEntity city = cityList.get(options1).get(options2);
                            //新建城市信息
                            CarriageSelectEntity entity = new CarriageSelectEntity();
                            entity.setNo(city.getNo());
                            entity.setName(city.getName());
                            List<CarriageSelectEntity> tags = mList.get(mSelectIndex).getList();
                            if (viewModel.checkRepeatCity(tags, city))
                                return;
                            tags.add(0, entity);
                            mAdapter.notifyDataSetChanged();
                        });
            }
        });
    }

    private void initRecycler() {
        mAdapter = new SubscriptionSetAdapter(mList);
        mBinding.rvAddressSet.setLayoutManager(new LinearLayoutManager(this));
//        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_list_divide_05));
//        mBinding.rvAddressSet.addItemDecoration(divider);
        mAdapter.bindToRecyclerView(mBinding.rvAddressSet);
    }

    /**
     * 编辑路线时设置老数据
     *
     * @param pathEntity
     */
    private void loadingData(OwnPathEntity pathEntity) {
        mList.clear();
        mList.add(new SubSetListEntity("请选择装货地 ", pathEntity.getCity()));
        mList.add(new SubSetListEntity("请选择目的地 ", pathEntity.getDestCity()));
        mAdapter.notifyDataSetChanged();
        String carTypeStr = "";
        if (pathEntity.getCarType() != null && pathEntity.getCarType().size() > 0) {
            carTypeEntities.clear();
            for (CarriageSelectEntity entity : pathEntity.getCarType()) {
                TypeChooseEntity typeEntity = new TypeChooseEntity();
                typeEntity.setName(entity.getName());
                typeEntity.setNo(entity.getNo());
                typeEntity.setSelect(true);
                carTypeEntities.add(typeEntity);
                if (!TextUtils.isEmpty(entity.getName())) {
                    carTypeStr = carTypeStr + entity.getName() + "/";
                }
            }
            if (carTypeStr.length() > 0) {
                carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
            }

        }
        if (TextUtils.isEmpty(carTypeStr)) {
            mBinding.chooseCarType.setText("请选择车型");
            mBinding.chooseCarType.setTextColor(this.getResources().getColor(R.color.color_C0C4CC));
        } else {
            mBinding.chooseCarType.setText(carTypeStr);
            mBinding.chooseCarType.setTextColor(this.getResources().getColor(R.color.color_ff666666));
        }


        if (pathEntity.getStatus().equals("1")) {
            //开启状态
            mBinding.switchBtn.setChecked(true);
        } else {
            //禁用状态
            mBinding.switchBtn.setChecked(false);
        }
    }
    private void setGoodsTypeData(List<TypeChooseEntity> selectEntities){
        String goodsTypeStr = "";
        if (pathEntity.getGoodsType() != null && pathEntity.getGoodsType().size() > 0) {
            goodsTypeEntities.clear();
            if (selectEntities!=null&&selectEntities.size()>0){
                for (int i = 0;i<selectEntities.size();i++){
                    selectEntities.get(i).setSelect(true);
                    goodsTypeEntities.add(selectEntities.get(i));
                    if (!TextUtils.isEmpty(selectEntities.get(i).getName())) {
                        goodsTypeStr = goodsTypeStr + selectEntities.get(i).getName() + "/";
                    }
                }
            }else {
                for (CarriageSelectEntity entity :pathEntity.getGoodsType()) {
                    TypeChooseEntity typeEntity = new TypeChooseEntity();
                    typeEntity.setName(entity.getName());
                    typeEntity.setNo(entity.getNo());
                    typeEntity.setSelect(true);
                    goodsTypeEntities.add(typeEntity);
                    if (!TextUtils.isEmpty(entity.getName())) {
                        goodsTypeStr = goodsTypeStr + entity.getName() + "/";
                    }
                }
            }

            if (goodsTypeStr.length() > 0) {
                goodsTypeStr = goodsTypeStr.substring(0, goodsTypeStr.length() - 1);
            }
            goodsTypeEditeList=goodsTypeEntities;
        }
        if (TextUtils.isEmpty(goodsTypeStr)) {
            mBinding.chooseGoodsType.setText("请选择货物类型");
            mBinding.chooseGoodsType.setTextColor(this.getResources().getColor(R.color.color_C0C4CC));
        } else {
            mBinding.chooseGoodsType.setText(goodsTypeStr);
            mBinding.chooseGoodsType.setTextColor(this.getResources().getColor(R.color.color_ff666666));
        }
    }

    private void initTags() {
        pathEntity = new OwnPathEntity();
        mList.clear();
        mList.add(new SubSetListEntity("请选择装货地 ", pathEntity.getCity()));
        mList.add(new SubSetListEntity("请选择目的地 ", pathEntity.getDestCity()));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.right_view:
                if (pathEntity != null && !TextUtils.isEmpty(pathEntity.getId())) {
                    deletePath(pathEntity.getId());
                }
                break;

            case R.id.choose_car_type:
                mSelectIndex = 2;
                carsTypePop.showDownPopwindow(mBinding.chooseCarType, true);
                carsTypePop.backgroundAlpha(0.5f);
                carsTypePop.setTittle("车型");
                break;

            case R.id.choose_goods_type:
                mSelectIndex = 3;
                goodsTypePop.showDownPopwindow(mBinding.chooseGoodsType, true);
                goodsTypePop.backgroundAlpha(0.5f);
                goodsTypePop.setTittle("货物类型");
                break;

            case R.id.submit_btn:
                pathEntity.setCity(mList.get(0).getList());
                pathEntity.setDestCity(mList.get(1).getList());
                pathEntity.setGoodsType(viewModel.selectToCarriage(goodsTypeEntities));
                pathEntity.setCarType(viewModel.selectToCarriage(carTypeEntities));
                viewModel.packagingData(this, pathEntity);
                break;
        }
    }

    private void deletePath(String id) {
        new RoundDialog.Builder(getActivity())
                .title("删除确认")
                .content("删除后将不再推送该线路货源，您确定要删除吗？")
                .cancel("取消")
                .confirm("确定")
                .confirmCallback(v -> {
                    if (!TextUtils.isEmpty(pathEntity.getId())) {
                        viewModel.deletePath(this, id);
                    }
                })
                .show();
    }

}
